package com.zidian.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.ChartOptionListAdapter;
import com.zidian.teacher.bean.TwoIndexBean;
import com.zidian.teacher.common.ColorConstants;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by GongCheng on 2017/1/10.
 */

public class StudentEvaTwoIndexActivity extends ToolBarActivity {
    @Bind(R.id.student_two_index_bar_chart)
    BarChart barChart;
    @Bind(R.id.eva_tag_rv)
    RecyclerView evaTagRv;

    private ChartOptionListAdapter adapter;
    private String indexName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_student_eva_two_index);
        Intent intent = getIntent();
        indexName = intent.getStringExtra("indexName");
        setTitle(indexName);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        evaTagRv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ChartOptionListAdapter();
        evaTagRv.setAdapter(adapter);
        initBarChart(barChart);
        getTwoIndex();
    }

    /**
     * 初始化条形图
     *
     * @param chart
     */
    private void initBarChart(BarChart chart) {
        chart.setDescription(null);
        //设置拦截所有触摸事件
        chart.setTouchEnabled(false);
        List<String> stringList = new ArrayList<>();

        XAxis xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(5);
        xAxis.setTextSize(10f);
        //X轴Value设计
//        xAxis.setValueFormatter(valueFormatter);
        xAxis.setGranularity(1);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return "";
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
        //Y轴左侧
        YAxis yl = chart.getAxisLeft();
        yl.setDrawAxisLine(true);
        yl.setDrawGridLines(false);
        yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        //Y轴右侧
        YAxis yr = chart.getAxisRight();
        yr.setDrawAxisLine(true);
        yr.setDrawGridLines(false);
        yr.setAxisMinimum(0f);
        chart.animateY(1500);
        //图表说明设置
        Legend l = chart.getLegend();
        l.setPosition(Legend.LegendPosition.ABOVE_CHART_RIGHT);
        l.setXEntrySpace(7f);
        l.setYOffset(0f);
        l.setEnabled(false);
    }

    /**
     * 得到BarChart的data
     *
     * @return
     */
    private BarData getBarData(List<TwoIndexBean.DataBean> data) {
        List<BarEntry> barEntries = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            barEntries.add(new BarEntry(i + 1, data.get(i).getTwoIndexScore()));
        }
        BarDataSet dataSet = new BarDataSet(barEntries, "BarChart");
        dataSet.setColors(ColorConstants.CHART_COLORS);
        BarData barData = new BarData(dataSet);
        barData.setBarWidth(0.3f);
        barData.setValueTextSize(12);
        return barData;
    }

    private void getTwoIndex() {
        String url = Constant.URL_TEACHER + "EvaluateByStudent/studentEvaluationTwoIndex";
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", GetUserInfo.getTeacherId(this));
        map.put("token", GetUserInfo.getToken(this));
        map.put("indexName", indexName);
        OkHttpUtils.post().params(map).url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast(context, "加载失败");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") != 200) {
                        Snackbar.make(evaTagRv, jsonObject.getString("message"),Snackbar.LENGTH_SHORT).show();
                    } else {
                        Gson gson = new Gson();
                        TwoIndexBean bean = gson.fromJson(response, TwoIndexBean.class);;
                        barChart.setData(getBarData(bean.getData()));
                        barChart.invalidate();
                        adapter.setData(bean.getData());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
